import {login, logout, getInfo, getInfoById} from '@/api/admin'
import {getToken, setToken, removeToken, setRoleId, getRoleId} from '@/utils/auth'
import {resetRouter} from '@/router'
import Vue from 'vue'

const getDefaultState = () => {
  return {
    token: getToken(),
    roleId: getRoleId(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ROLE_ID: (state, roleId) => {
    state.roleId = roleId
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password}).then(response => {
        const {data} = response.data
        console.log(data)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        commit('SET_ROLE_ID', data.operator.id)
        setRoleId(data.operator.id)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response.data
        console.log(data)
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const {name, avatar} = data
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getInfoById({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfoById(state.roleId).then(response => {
        const {data} = response.data
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const {username, avatar} = data
        const httpAvatar = Vue.prototype.$getImg(avatar)
        commit('SET_NAME', username)
        commit('SET_AVATAR', httpAvatar)
        resolve(data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

